package com.citic.netty.common.serializer.impl;

import com.citic.netty.common.exception.NettyRuntimeException;
import com.citic.netty.common.serializer.Serializer;
import com.citic.netty.common.serializer.SerializerAlgorithm;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonSerializer implements Serializer{

	@Override
	public byte getSerializerAlogrithm() {
		return SerializerAlgorithm.JSON;
	}

	@Override
	public byte[] serialize(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsBytes(object);
		} catch (Exception e) {
			throw new NettyRuntimeException("json serialize error: " + e.getMessage());
		}
	}

	@Override
	public <T> T deserialize(Class<T> clazz, byte[] bytes) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(bytes, clazz);
		} catch (Exception e) {
			throw new NettyRuntimeException("json deserialize error: " + e.getMessage());
		} 
	}

}
